package softtech.apps.callblocker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import softtech.apps.utility.ApplicationConstants;
import softtech.apps.utility.FileUtility;
import softtech.apps.callblocker.adapter.AdapterHomeManager;
import softtech.apps.callblocker.model.BlackListItem;
import softtech.apps.callblocker.model.CallBlockedItem;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.Setting;
import softtech.apps.callblocker.model.SmsBlockedItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ActivityDashboard extends Activity {

	static final String TAG = "Activity Dashboard";

	Context context;

	static Boolean isLogin = false;

	/**
	 * Main fliper use to change page / layout
	 */
	ViewFlipper vflipMain;

	/**
	 * Animation of vflipMain
	 */
	Animation slide_in_left, slide_out_right;

	/**
	 * Selected position of vflipMain
	 */
	int currentPage;

	/**
	 * Home page
	 */
	AdapterHomeManager adapter;
	ListView lvHomeManager;

	/**
	 * linear security
	 */
	// Radio Button security form
	RadioButton rabtnConfirm1, rabtnConfirm2, rabtnConfirm3, rabtnConfirm4;

	/**
	 * Security Form
	 */
	ArrayList<ImageButton> listSecurityImageButton;

	ImageButton ibtnClearSecurityKey;

	String securityPass, truePass, fakePass;

	public static int successLogin = 1;

	DatabaseHanler db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dashboard);
		context = this;
		db = new DatabaseHanler(context);
		audioringer();
		testcall();
		
		//
		//
//		Setting setting = new Setting();
//		DatabaseHanler db = new DatabaseHanler(context);
//		setting = db.getSetting(null);
//		Toast.makeText(context, ""+setting.getDefaultModel(), Toast.LENGTH_LONG
//				).show();
		//
		// send action widget
		//
		sendIntentWidget();
		setId();
		init();
		setFunction();

		if (isLogin) {
			Log.e(TAG , "success " + successLogin);
			if(successLogin != 1){
				selectPage(0);
			}else{
				selectPage(1);
			}
			
		} else {
			if (!checkIsHavePassCode()) {
				selectPage(1);
			}
		}

		if (checkFreeTrialFinished()) { // not activated
			setFunctionWhenOutOfDateTrial();
		} else { // activated or in free trial time
			setFunctionWhenActivateOrInTrial();

		}
		startService();
	}
/**
 * get audio ringer
 */
	private void audioringer() {
		//ringer mode
		AudioManager audiomanage = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
		ApplicationConstants.AUDIO_RINGER=audiomanage.getRingerMode();
	}

	/**
	 * Set id for any view in ActivityDashboard
	 */
	void setId() {
		vflipMain = (ViewFlipper) findViewById(R.id.vflipMain);

		// set id for home page
		lvHomeManager = (ListView) findViewById(R.id.lvHomeManager);

		setIdForSecurityForm();
		
	}

	/**
	 * init animation, first page for vflipMain
	 */
	void initForFlipMain() {
		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		vflipMain.setInAnimation(slide_in_left);
		vflipMain.setOutAnimation(slide_out_right);
		currentPage = 0;
	}

	/**
	 * Go to the new page of vflipmain
	 * 
	 * @param page
	 *            : position that you want to transfer
	 */
	void selectPage(int page) {

		String title_name = "";

		switch (page) {
		case 0:
			break;

		default:
			break;
		}
		if (title_name.contentEquals("")) {
			title_name = getResources().getString(R.string.app_name);
		}
		vflipMain.setDisplayedChild(page);
		this.getActionBar().setTitle(title_name);
	}

	/**
	 * set function for all view in activity
	 */
	void setFunction() {
		setFunctionForSecurityForm();
	}

	/**
	 * set function when out of date trial
	 */
	void setFunctionWhenOutOfDateTrial() {
		lvHomeManager.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent inBuyInApp = new Intent(ActivityDashboard.this,
						ActivityActiveApplication.class);
				startActivity(inBuyInApp);
				finish();
			}
			
		});
	}

	/**
	 * set function when activated or in trial time
	 */
	void setFunctionWhenActivateOrInTrial() {
		lvHomeManager.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (successLogin != 1) {
					return;
				}
				actionWithHome(position);
			}
		});
	}

	/**
	 * init value, display for activity
	 */
	void init() {
		if(!isLogin){
			successLogin = 1;
		}
		
		initLisenceFile();
		initHome();
		initSecurityForm();
		initPassCode();
		initSetting();
	}

	/**
	 * init variable setting
	 */
	void initSetting() {
		db = new DatabaseHanler(context);
		Setting setting = db.getSetting(null);

		if (setting == null || setting.equals(null)) {
			// create setting & insert to database
			setting = new Setting("", "", 17, 1, 1);
			db.insertSetting(setting);
		}
	}

	/**
	 * start service
	 */
	void startService() {
		context.startService(new Intent(context, ServiceDateTimeChange.class));
	}

	/**
	 * Init for home page
	 */
	void initHome() {
		adapter = new AdapterHomeManager(context);
		lvHomeManager.setAdapter(adapter);
	}

	/**
	 * Set function for controls in security form
	 */
	void setFunctionForSecurityForm() {
		for (int i = 0; i < 10; i++) {
			listSecurityImageButton.get(i).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							((Vibrator) getSystemService(VIBRATOR_SERVICE))
									.vibrate(100);
							securityPass += v.getTag().toString();
							Log.e(TAG, v.getTag().toString() + " "
									+ securityPass);
							if (securityPass.length() == 4) {
								rabtnConfirm4.setChecked(true);
								if (securityPass.contentEquals(truePass)) {
									vflipMain.showNext();
									successLogin = 1;
									isLogin = true;
								} else if (securityPass.contentEquals(fakePass)) {
									successLogin = 2;
									isLogin = true;
									AlertDialog.Builder b = new AlertDialog.Builder(
											context);
									b.setTitle("Success.");
									b.setMessage("Login success!!!");

									b.setNegativeButton(
											"OK",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {

													openCompanyPageOnPlayStore();
													ActivityDashboard.this
															.finish();
												}
											});
									b.show();
								} else {
									successLogin = 0;
									initSecurityForm();
								}

							} else {
								if (securityPass.length() == 1) {
									rabtnConfirm1.setChecked(true);
								}
								if (securityPass.length() == 2) {
									rabtnConfirm2.setChecked(true);
								}
								if (securityPass.length() == 3) {
									rabtnConfirm3.setChecked(true);
								}
								if (securityPass.length() == 4) {
									rabtnConfirm4.setChecked(true);
								}
							}
						}
					});
		}

		ibtnClearSecurityKey.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				securityPass = "";
				initSecurityForm();
			}
		});
	}

	/**
	 * Init Security Form
	 */
	void initSecurityForm() {
		securityPass = "";

		rabtnConfirm1.setChecked(false);
		rabtnConfirm2.setChecked(false);
		rabtnConfirm3.setChecked(false);
		rabtnConfirm4.setChecked(false);
	}

	/**
	 * Init the passCode
	 */
	void initPassCode() {
		truePass = "";
		fakePass = "";
		
	}

	/**
	 * set id for security form
	 */
	void setIdForSecurityForm() {
		// Security form

		rabtnConfirm1 = (RadioButton) findViewById(R.id.rabtnConfirm1);
		rabtnConfirm2 = (RadioButton) findViewById(R.id.rabtnConfirm2);
		rabtnConfirm3 = (RadioButton) findViewById(R.id.rabtnConfirm3);
		rabtnConfirm4 = (RadioButton) findViewById(R.id.rabtnConfirm4);

		ibtnClearSecurityKey = (ImageButton) findViewById(R.id.ibtnClearSecurityKey);

		listSecurityImageButton = new ArrayList<ImageButton>();
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber0));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber1));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber2));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber3));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber4));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber5));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber6));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber7));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber8));
		listSecurityImageButton
				.add((ImageButton) findViewById(R.id.ibtnSecurityNumber9));
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	/**
	 * Action when listview click Move to activity or excute action
	 * 
	 * @param position
	 */
	private void actionWithHome(int position) {
		switch (position) {
		case 0: // enable / disable function block call
			if (TextEnable.getEnableApp(context) == 0) {
				TextEnable.fTextCreate("1", context);
			} else {
				TextEnable.fTextCreate("0", context);
			}
			adapter.notifyDataSetChanged();
			break;
		case 1: // buy in app

			Intent inBuyInApp = new Intent(ActivityDashboard.this,
					ActivityActiveApplication.class);
			startActivity(inBuyInApp);
			finish();
			break;
		case 2: // blacklist
			Intent inBlacklist = new Intent(ActivityDashboard.this,
					ActivityShowBlackListItem.class);
			startActivity(inBlacklist);
			finish();
			break;
		case 3:// history
			Intent inHistory = new Intent(ActivityDashboard.this,
					ActivityCallHistory.class);
			startActivity(inHistory);
			finish();
			break;
		case 4: // Setting
			Intent inSetting = new Intent(ActivityDashboard.this,
					ActivitySettings.class);
			startActivity(inSetting);
			finish();
			break;
		case 5: // about us
			Intent inAbout = new Intent(ActivityDashboard.this,
					ActivityAboutUs.class);
			startActivity(inAbout);
			finish();
			break;
		default:
			break;
		}
	}

	/**
	 * init license file if not exist
	 */
	void initLisenceFile() {

		FileUtility futil = new FileUtility();

		//
		// init file limited
		//
		int limited_date = 30;
		try {

			limited_date = Integer.parseInt(futil.LoadContentFile(context,
					ApplicationConstants.FILE_LIMITED));

			if (limited_date == 0) {
				futil.SaveContentFile(context,
						ApplicationConstants.FILE_LIMITED, "" + limited_date);
			}
		} catch (Exception e) {
			futil.SaveContentFile(context, ApplicationConstants.FILE_LIMITED,
					"" + limited_date);
		}

		//
		// create folder
		//
		FileUtility
				.createDirIfNotExists(ApplicationConstants.PATH_FOLDER_LICENSE);

		//
		// check old file
		//
		String old_file_sdcard = futil.getContentFileFromSdcard(
				ApplicationConstants.PATH_FOLDER_LICENSE,
				ApplicationConstants.FILE_LICENSE_NAME);
		String old_file_in_app = futil.LoadContentFile(context,
				ApplicationConstants.FILE_LICENSE_NAME);

		if (FileUtility.checkStringNotNull(old_file_sdcard)
				&& FileUtility.checkStringNotNull(old_file_in_app)) {
			return;
		}

		//
		// create file if not exist
		//
		if (!FileUtility.checkStringNotNull(old_file_sdcard)) {
			futil.saveContentFileToSdCard("0",
					ApplicationConstants.PATH_FOLDER_LICENSE,
					ApplicationConstants.FILE_LICENSE_NAME);
		}

		if (!FileUtility.checkStringNotNull(old_file_in_app)) {
			futil.SaveContentFile(context,
					ApplicationConstants.FILE_LICENSE_NAME, "0");
		}

	}

	/**
	 * check free trial finished
	 * 
	 * @return true: out of date false: in free time or activated
	 */
	Boolean checkFreeTrialFinished() {
		FileUtility futil = new FileUtility();

		//
		// check license
		//
		if (checkIsActivated()) {
			return false;
		}

		//
		// check free time
		//
		int value1 = 0;
		int value2 = 0;
		int currentvalue = 0;
		// get old value
		try {
			value1 = Integer.parseInt(futil.getContentFileFromSdcard(
					ApplicationConstants.PATH_FOLDER_LICENSE,
					ApplicationConstants.FILE_LICENSE_NAME).trim());
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			value2 = Integer.parseInt(futil.LoadContentFile(context,
					ApplicationConstants.FILE_LICENSE_NAME).trim());
		} catch (Exception e) {
			e.printStackTrace();
		}

		currentvalue = Math.max(value1, value2);

		if (currentvalue >= ApplicationConstants.MAX_TIME_FREE) {
			return true;
		}
		return false;
	}

	/**
	 * check if user is activated
	 * 
	 * @return true: activated false: not activate
	 */
	Boolean checkIsActivated() {
		FileUtility futil = new FileUtility();

		//
		// check license
		//
		int value1 = 0;
		int value2 = 0;
		int currentvalue = 0;
		// get old value
		try {
			value1 = Integer.parseInt(futil.getContentFileFromSdcard(
					ApplicationConstants.PATH_FOLDER_LICENSE,
					ApplicationConstants.FILE_ACTIVATE_NAME).trim());
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			value2 = Integer.parseInt(futil.LoadContentFile(context,
					ApplicationConstants.FILE_ACTIVATE_NAME).trim());
		} catch (Exception e) {
			e.printStackTrace();
		}

		currentvalue = value1 & value2;

		if (value1 == 0) {
			futil.saveContentFileToSdCard(String.valueOf(currentvalue),
					ApplicationConstants.PATH_FOLDER_LICENSE,
					ApplicationConstants.FILE_ACTIVATE_NAME);

		}

		if (value2 == 0) {
			futil.SaveContentFile(context,
					ApplicationConstants.FILE_ACTIVATE_NAME,
					String.valueOf(currentvalue));
		}

		if (currentvalue == 1) {
			return true;
		}
		return false;
	}

	/**
	 * check have pass code
	 * 
	 * @return true : have pass code false : not have pass code
	 */
	Boolean checkIsHavePassCode() {
		try {
			Setting appSetting = db.getSetting(null);
			truePass = appSetting.getPassCode();

			fakePass = appSetting.getPassFakeCode();
			Log.e(TAG, "fake pass = " + fakePass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (FileUtility.checkStringNotNull(truePass)) {
			return true;
		}

		return false;
	}

	/**
	 * Create widget on home screen
	 */
	public void sendIntentWidget() {
		Intent inWidget = new Intent("callblocker.widget.ACTIVE");
		context.sendBroadcast(inWidget);

	}

	/**
	 * Open company page
	 */
	void openCompanyPageOnPlayStore() {
		Uri uri = Uri.parse("market://apps/collection/Soft+Tech+VN");
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
			startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
			startActivity(new Intent(
					Intent.ACTION_VIEW,
					Uri.parse("https://play.google.com/store/apps/developer?id=Soft+Tech+VN")));
		}
	}
	
	
	/**
	 * test call history
	 */
	void testcall(){
//		SmsBlockedItem item = null;
//		CallBlockedItem item2 = null;
//		Calendar cal = Calendar.getInstance();
//		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
//		String datetime = df.format(cal.getTime());
//		for(int i = 0 ; i < 50 ; i ++){
//			item = new SmsBlockedItem("12345", datetime, SmsBlockedItem.RECEIVE , "that la buon qua di ma");
//			item2 = new CallBlockedItem("12345", datetime, 1);
//			Log.e(TAG , "date time = "+ datetime);
//			db.insertSmsBlockItem(item);
//			db.insertCallBlockItem(item2);
//		}
		
		BlackListItem item = null;
		for(int i = 0 ; i < 30 ; i++){
			item = new BlackListItem("1234"+ i, "a" + i + "vkl" , 17);
			db.insertBlackListItem(item);
		}
		
		for(int i = 0 ; i < 30 ; i++){
			item = new BlackListItem("234"+ i, "b" + i + "vkl" , 17);
			db.insertBlackListItem(item);
		}
		
		for(int i = 0 ; i < 30 ; i++){
			item = new BlackListItem("334"+ i, "c" + i + "vkl" , 17);
			db.insertBlackListItem(item);
		}
		for(int i = 0 ; i < 30 ; i++){
			item = new BlackListItem("434"+ i, "d" + i + "vkl" , 17);
			db.insertBlackListItem(item);
		}
			
		
	}
}
